<template>
  <div>
    <el-button type="text" @click="dialogVisible = true">添加一级分类</el-button><br>
    <!-- 拖拽开关 -->
    <el-switch
      v-model="draggable"
      active-text=""
      inactive-text="拖拽开关">
  </el-switch>
  <el-button v-if="draggable" @click="batchSave()" size="mini" round>保存拖拽</el-button>
  <el-button type="danger" @click="batchDelete" size="mini" round>批量删除</el-button>
    <!-- 树形分类 -->
    <el-tree
      :data="menus"
      :props="defaultProps"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKey"
      :expand-on-click-node="false"
      :draggable="draggable" 
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >添加</el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => edit(data)"
          >修改</el-button>
          <el-button
            v-if="node.childNodes.length==0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >删除</el-button>
        </span>
      </span>
    </el-tree>
    <!-- 对话框 -->
    <!-- 是否可以通过点击modal关闭Dialog flase -->
    <el-dialog :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false"> 
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
     
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click= submitData()>确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pCid: [],
      draggable: false,
      updateNodes: [], // 拖拽后要更新的数据
      maxLevel: 0,    // 拖拽节点的深度
      title: "",
      dialogType: "", // edit,add
      category: {     // 表单绑定数据 
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        productUnit: "",
        icon: "",
        catId: null
      },
      expandedKey: [],
      menus: [], // 树形分类绑定数据
      defaultProps: {
        children: "children",
        label: "name"
      },
      dialogVisible: false
    };
  },
  methods: {
    getMenus() {
      this.$http({
        url: this.$http.adornUrl(`/product/category/list/tree`),
        method: "get"
      }).then(response => {
        this.menus = response.data.data;
        console.log(`分类集合获取成功`, this.menus);
      });
    },
     batchDelete() {
      let catIds = [];
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      console.log("被选中的元素", checkedNodes);
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId);
      }
      this.$confirm(`是否批量删除菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false)
          }).then(({ data }) => {
            this.$message({
              message: "菜单批量删除成功",
              type: "success"
            });
            this.getMenus();
          });
        })
        .catch(() => {});
    },
    // 保存拖拽， 提交数据
    batchSave() {
      this.$http({
        url: this.$http.adornUrl(`/product/category/update/sort`),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false)
      })
      .then(({data}) => {
        this.$message({
          message: `拖拽成功，更新层级顺序等`,
          type: 'success'
        })
        this.getMenus()
        this.expandedKey = this.pCid
        this.updateNodes = []
        this.maxLevel = 0
        // this.pCid = 0

      })
    },
    // 拖拽节点判断
    allowDrop(draggingNode, dropNode, type) {
      // 获取正在拖动的当前节点的最大深度
     this.countNodeLevel(draggingNode)
     // 计算正在拖动节点的总层数
     console.log("最大深度：", this.maxLevel);
     let deep = Math.abs( this.maxLevel - draggingNode.level ) +1
     if(draggingNode.childNodes == null || draggingNode.childNodes.length == 0) {
       deep = 1
     }
     console.log("层数：", deep);
     if(type == 'inner') {
       console.log("inner：", deep + dropNode.level);
       return Math.abs(deep + dropNode.level) <= 3
       
     } else {
        return (deep + dropNode.parent.level) <= 3;
        console.log('before deep ',deep + dropNode.parent.level)
      } 
      
    },
    //找到所有子节点，求出最大深度/level
    countNodeLevel(node) {
      if(node.childNodes != null && node.childNodes.length > 0) {
        for(let i = 0; i < node.childNodes.length; i++) {
          if(node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },
    // 拖拽成功完成时触发的事件
    // 共四个参数，依次为：被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置（before、after、inner）、event
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log('tree drop: ', draggingNode, dropNode, dropType);
      // 当前节点最新的父id 和 同科兄弟
      let pCid = 0
      let siblings = null;
      if(dropType == "before" || dropType == "after") {
        pCid = dropNode.parent.data.catId == undefined? 0:dropNode.parent.data.catId
        siblings = dropNode.parent.childNodes;
        // console.log('siblings', siblings)
      } else {
        pCid = dropNode.data.catId
        siblings = dropNode.childNodes
      }
      this.pCid.push(pCid)
      
      //  当前拖拽节点的最新顺序    ++++++++++++++++++++++++++++++++++++
      for(let i = 0; i < siblings.length; i++) {
        // 如果遍历的是当前正在拖拽的节点
        if(siblings[i].data.catId === draggingNode.data.catId) {
          let catLevel = draggingNode.level
          // 如果拖拽后节点发生变化
          if(siblings[i].level != draggingNode.level) {
            catLevel = siblings[i].level
            //修改他子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          // 当前节点需要更新的数据
          this.updateNodes.push({
            parentCid: pCid, 
            catId: siblings[i].data.catId, 
            sort: i,
            catLevel: catLevel
            })
        }
        // 拖拽后原来的节点只更新排序by catId
        this.updateNodes.push({catId: siblings[i].data.catId, sort: i})
      }
       // 当前拖拽节点成功后，所有需要更新的数据
      console.log("updateNodes", this.updateNodes);
      
    },
    // 更新拖拽后的子节点层级  
    updateChildNodeLevel(node) {
      if(node.childNodes.length > 0) {
        for(let i = 0; i < node.childNodes.length; i++) {
          // 封装当前遍历子节点的data数据
          let cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level
          })
          this.updateChildNodeLevel(node.childNodes[i])
        }
      }
    },
    // 添加或修改  提交确认
    submitData() {
      if(this.category.catId === null) {
        this.addCategory()
      } else {
        this.editCategory()
      }
    },
    // 提交 确认添加分类
    addCategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      })
      .then(({data}) => {
        this.$message({
          message: "菜单保存成功",
          type: "success"
        });
        //关闭对话框
        this.dialogVisible = false;
        //刷新出新的菜单
        this.getMenus();
        //设置需要默认展开的菜单
        this.expandedKey = [this.category.parentCid];
      
      })
    },
    // 提交 确认修改分类
    editCategory() {
      // 结构需要更新的数据
      let { catId, name, icon, productUnit } = this.category;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: 'post',
        data: this.$http.adornData({ catId, name, icon, productUnit }, false)
      })
     .then(({ data }) => {
        this.$message({
          message: "菜单修改成功",
          type: "success"
        });
        //关闭对话框
        this.dialogVisible = false;
        //刷新出新的菜单
        this.getMenus();
        //设置需要默认展开的菜单
        this.expandedKey = [this.category.parentCid];
      })
      .catch((error) => {
        this.$message({
          message: "菜单修改失败",
          type: "error"
        });
      });
    },

    // 添加分类框
    append(data) {
      this.dialogVisible = true;

      this.title = "添加分类";
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1; // 字符串转int
      this.category.catId = null;
      this.category.name = "";
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.sort = 0;
      this.category.showStatus = 1;
      console.log("append", this.category);
    },
        // 修改分类
    edit(data) {
      console.log('要修改的数据', data)
      this.title = "修改分类";
      this.dialogVisible = true;
      //发送请求获取当前节点最新的数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get"
      })
      .then(({data}) => {
        //请求成功
        console.log("要回显的数据", data);
        this.category.name = data.data.name;
        this.category.catId = data.data.catId;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.parentCid = data.data.parentCid;

        // this.category.catLevel = data.data.catLevel;
        // this.category.sort = data.data.sort;
        // this.category.showStatus = data.data.showStatus;
      })

    },
    // 删除分类
    remove(node, data) {
      let ids = [data.catId];
      this.$confirm(`是否删除[${data.name}]菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl(`/product/category/delete`),
            method: "post",
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            this.$message({
              message: "菜单删除成功",
              type: "success"
            });
            // 刷新菜单
            this.getMenus();
            // 设置默认展开的菜单
            this.expandedKey = [node.parent.data.catId];
          });
        })
        .catch(() => {});

      console.log("remove", node, data);
    }
  },
  created() {
    this.getMenus();
  }
};
</script>

<style>
</style>